<?php

namespace Admin\Controller;

use Think\Controller;
use Think\Image;
use Think\Page;
use Org\Net\Http;

class OrderController extends AuthController {
	/**
	 * 获取添加订单
	 */
	public function index() {
		if (IS_POST) {
			$staff = session ( "auth" );
			$data ['staff'] = $staff ['name'];
			$nums = $_POST ['num'];
			$order = D ( "Order" );
			$data ['uid'] = $_POST ['uid'];
			$data ['remark'] = $_POST ['remark'];
			$data ['address'] = $_POST ['address'];
			$data ['area'] = $_POST ['area'];
			$data ['phone'] = $_POST ['phone'];
			$data ['username'] = $_POST ['name'];
			$data ['payment'] = $_POST ['payment'];
			$data ['ptime'] = $_POST ['ptime'];
			$where ['FoodCategory.id'] = array (
					"in",
					$_POST ['category'] 
			);
			$data = $order->create ( $data );
			// var_dump($where);
			$result = $order->add ( $data );
			if ($result) {
				$foods = D ( "FoodCategory" )->where ( $where )->select ();
				// $foods = D ( 'Food' )->where ( $where )->field ( "id as fid,food_name,food_image,yprice,price,unit" )->select ();
				$count = count ( $foods );
				$i = 0;
				$food_yprice = 0;
				$food_price = 0;
				$carrige_price = 0;
				$oddata = array ();
				foreach ( $foods as $food ) {
					$food ['num'] = $nums [$i];
					$food ['oid'] = $data ['id'];
					$oddata [] = $food;
					$food_yprice += $food ['yprice'] * $food ['num'];
					$food_price += $food ['price'] * $food ['num'];
					$i ++;
				}
				M ( 'OrderDetail' )->addAll ( $oddata );
				$data ['food_yprice'] = $food_yprice;
				$data ['food_price'] = $food_price;
				$result = $order->where ( array (
						'id' => $data ['id'] 
				) )->save ( $data );
				if ($result) {
					$this->success ( "添加订单成功", "index" );
				} else {
					$this->error ( "修改订单信息出错" );
				}
			} else {
				$this->error ( "添加订单出错" );
			}
		} else {
			$users = M ( 'User' )->order ( array (
					'id' => 'asc' 
			) )->select ();
			$areas = M ( 'Area' )->order ( array (
					'id' => 'asc' 
			) )->select ();
			$foods = M ( 'Food' )->order ( array (
					'id' => 'asc' 
			) )->select ();
			$otimes = M ( 'OrderTime' )->order ( array (
					'id' => 'asc' 
			) )->select ();
			$this->assign ( 'users', $users );
			$this->assign ( 'areas', $areas );
			$this->assign ( 'foods', $foods );
			$ptimes = array ();
			foreach ( $otimes as $otime ) {
				if ($otime ['status']) {
					$ptime = "";
					switch ($otime ['type']) {
						case 1 :
							$ptime .= "当天";
							break;
						case 2 :
							$ptime .= "次日";
							break;
					}
					$ptime .= "{$otime['stime']}-{$otime['etime']}";
					$ptimes [] = $ptime;
				}
			}
			$this->assign ( 'ptimes', $ptimes );
			$this->display ();
		}
	}
	/**
	 * 订单列表
	 */
	public function orderlist() {
		$list = M ()->query ( "SELECT o.*,u.name,u.account,u.phone_number FROM vw_order o LEFT JOIN vw_user u ON o.uid=u.id ORDER BY o.cdate DESC,o.ctime DESC" );
		$otimes = M ( 'OrderTime' )->order ( array (
				'id' => 'asc' 
		) )->select ();
		$this->assign ( 'list', $list );
		// file_put_contents("Public/Log/log.txt", "list:".json_encode($list)."\r\n",FILE_APPEND|LOCK_EX);
		$ptimes = array ();
		foreach ( $otimes as $otime ) {
			// if ($otime ['status']) {
			$ptime = "";
			switch ($otime ['type']) {
				case 1 :
					$ptime .= "当天";
					break;
				case 2 :
					$ptime .= "次日";
					break;
			}
			$ptime .= "{$otime['stime']}-{$otime['etime']}";
			$ptimes [] = $ptime;
			// }
		}
		$this->assign ( 'ptimes', $ptimes );
		$this->display ();
	}
	/**
	 * 选择配送
	 */
	public function choose() {
		$oids = split ( ",", I ( 'oids' ) );
		$where ['id'] = array (
				"in",
				$oids 
		);
		$data ['status'] = I ( 'status' ) + 1;
		$result = D ( 'Order' )->where ( $where )->save ( $data );
		$this->ajaxReturn ( $oids );
	}
	/**
	 * 每日统计
	 */
	public function summary() {
		if (IS_POST) {
			$cdate = I ( 'cdate' );
			$area = I ( 'area' );
			$ptime = I ( 'ptime' );
			$where = "";
			if ($cdate) {
				$where .= "AND cdate = '{$cdate}'";
			} else {
				$where .= "AND cdate = '" . date ( 'Y-m-d' ) . "'";
			}
			if ($area) {
				$where .= "AND area = '{$area}'";
			}
			if ($ptime) {
				$where .= "AND ptime = '{$ptime}'";
			}
			$result = M ()->query ( "SELECT od.unit,od.food_name,od.category, SUM(od.num) as num,f.food_tag,f.type FROM vw_order o,vw_order_detail od LEFT JOIN vw_food f ON od.food_name = f.food_name  WHERE od.oid = o.id {$where} GROUP BY od.cid  ORDER BY f.type ASC,f.food_tag ASC" );
			$this->ajaxReturn ( $result );
		} else {
			$where .= "AND cdate = '" . date ( 'Y-m-d' ) . "'";
			$result = M ()->query ( "SELECT od.unit,od.food_name,od.category, SUM(od.num) as num,f.food_tag,f.type FROM vw_order o,vw_order_detail od LEFT JOIN vw_food f ON od.food_name = f.food_name  WHERE od.oid = o.id {$where} GROUP BY od.cid  ORDER BY f.type ASC,f.food_tag ASC" );
			// $result = M ()->query ( "SELECT od.unit,od.food_name, SUM(od.num) as num FROM vw_order_detail od,vw_order o WHERE od.oid = o.id {$where} GROUP BY od.food_name ORDER BY od.id ASC" );
			$areas = M ( 'Area' )->order ( array (
					'id' => 'asc' 
			) )->select ();
			$otimes = M ( 'OrderTime' )->order ( array (
					'id' => 'asc' 
			) )->select ();
			$ptimes = array ();
			foreach ( $otimes as $otime ) {
				// if($otime['status']){
				// }
				$ptime = "";
				switch ($otime ['type']) {
					case 1 :
						$ptime .= "当天";
						break;
					case 2 :
						$ptime .= "次日";
						break;
				}
				$ptime .= "{$otime['stime']}-{$otime['etime']}";
				$ptimes [] = $ptime;
			}
			$this->assign ( 'areas', $areas );
			$this->assign ( 'ptimes', $ptimes );
			$this->assign ( 'list', $result );
			$this->display ();
		}
	}
	// 订单配送时间页面
	public function timeSet() {
		$orderTime = M ( 'OrderTime' );
		$list = $orderTime->order ( array (
				'id' => 'asc' 
		) )->select ();
		$this->assign ( 'list', $list );
		$this->display ();
	}
	// 添加日期操作
	public function addDate() {
		$data = array (
				'stime' => I ( 'stime' ),
				'etime' => I ( 'etime' ),
				'area' => I ( 'area' ),
				'type' => I ( 'type' ) 
		);
		if (isset ( $data )) {
			M ( 'OrderTime' )->add ( $data );
			$this->ajaxReturn ( array (
					'res' => 1 
			), 'json' );
		} else {
			$this->ajaxReturn ( array (
					'res' => - 1,
					'msg' => '添加失败' 
			), 'json' );
		}
	}
	// 编辑日期操作
	public function editDate() {
		$data = array (
				'stime' => I ( 'stime' ),
				'etime' => I ( 'etime' ),
				'area' => I ( 'area' ),
				'type' => I ( 'type' ) 
		);
		if (isset ( $data )) {
			M ( 'OrderTime' )->where ( array (
					'id' => I ( 'id' ) 
			) )->save ( $data );
			$this->ajaxReturn ( array (
					'res' => 1 
			), 'json' );
		} else {
			$this->ajaxReturn ( array (
					'res' => - 1,
					'msg' => '添加失败' 
			), 'json' );
		}
	}
	// 改变配送时间状态
	public function changeStatus() {
		$id = I ( 'tid' );
		$result = M ( 'OrderTime' )->where ( array (
				'id' => $id 
		) )->setField ( 'status', I ( 'status' ) );
		if (isset ( $result )) {
			$this->ajaxReturn ( array (
					'state' => 1 
			), 'json' );
		}
	}
	// 打开编辑日期model的时候获取信息
	public function getInfo() {
		$id = I ( 'id' );
		$result = M ( 'OrderTime' )->where ( array (
				'id' => $id 
		) )->find ();
		if (isset ( $result )) {
			$this->ajaxReturn ( $result );
		}
	}
	// 删除配送时间
	public function delTime() {
		$id = I ( 'id' );
		if ($id != null && $id != "") {
			$result = M ( 'OrderTime' )->where ( array (
					'id' => $id 
			) )->delete ();
			if (isset ( $result )) {
				$this->ajaxReturn ( array (
						'res' => '1' 
				), 'json' );
			} else {
				$this->ajaxReturn ( array (
						'res' => '-1',
						'msg' => '删除失败！' 
				), 'json' );
			}
		}
	}
	public function getData() {
		$time = I ( 'time' );
		$area = I ( 'area' );
		$status = I ( 'status' );
		$order = D ( 'OrderView' );
	}
	public function test() {
		$data = "2015-07-15";
		$data = strtotime ( $data );
		$end = $data + 86399;
		echo $end;
	}
	/*
	 * //订单列表页面
	 * public function orderList(){
	 * $order=D('OrderView');
	 * //未配送
	 * $count1 = $order->where('orders.pay_status = 1')->count();
	 * $list1 = $order->where('orders.pay_status = 1')->order('ctime desc')->select();
	 * // $page1 = new Page($count1,15);
	 * // $page1->setConfig('prev', '上页');
	 * // $page1->setConfig('next', '下页');
	 * // $show1 = $page1->show();
	 * for($i=0;$i<5;$i++){
	 * $list1 = array_merge($list1, $list1);
	 * }
	 * $this->list1=$list1;//页面数据
	 * $this->page1=$show1;
	 * $this->order=1;
	 * $this->orderList=1;
	 * $this->display();
	 * }
	 */
	// 订单详情页面
	public function details() {
		$oid = I ( 'id' );
		$orderInfo = M ()->query ( "SELECT o.cdate,o.ctime,o.ptime,o.remark,o.food_price as total_price,o.area,o.address,o.username as name,o.phone as phone_number,u.account FROM vw_order o LEFT JOIN vw_user u ON o.uid=u.id where o.id='{$oid}'" );
		$where ['oid'] = $oid;
		$list = M ( "OrderDetail" )->where ( $where )->select ();
		$this->assign ( "list", $list );
		$this->assign ( "info", $orderInfo );
		$this->display ();
	}
	
	// 导入数据方法
	public function goods_import($exts = 'xlsx') {
		// 导入PHPExcel类库，因为PHPExcel没有用命名空间，只能inport导入
		import ( "Org.Util.PHPExcel" );
		// 创建PHPExcel对象，注意，不能少了\
		$PHPExcel = new \PHPExcel ();
		// 如果excel文件后缀名为.xls，导入这个类
		if ($exts == 'xls') {
			import ( "Org.Util.PHPExcel.Reader.Excel5" );
			$PHPReader = new \PHPExcel_Reader_Excel5 ();
		} else if ($exts == 'xlsx') {
			import ( "Org.Util.PHPExcel.Reader.Excel2007" );
			$PHPReader = new \PHPExcel_Reader_Excel2007 ();
		}
		
		// 载入文件
		$PHPExcel = $PHPReader->load ( "Public/Upload/Excel/a111.xlsx" );
		// 获取表中的第一个工作表，如果要获取第二个，把0改为1，依次类推
		$currentSheet = $PHPExcel->getSheet ( 0 );
		// 获取总列数
		$allColumn = $currentSheet->getHighestColumn ();
		// 获取总行数
		$allRow = $currentSheet->getHighestRow ();
		// 循环获取表中的数据，$currentRow表示当前行，从哪行开始读取数据，索引值从0开始
		for($currentRow = 1; $currentRow <= $allRow; $currentRow ++) {
			// 从哪列开始，A表示第一列
			for($currentColumn = 'A'; $currentColumn <= $allColumn; $currentColumn ++) {
				// 数据坐标
				$address = $currentColumn . $currentRow;
				// 读取到的数据，保存到数组$arr中
				$data [$currentRow] [$currentColumn] = $currentSheet->getCell ( $address )->getValue ();
			}
		}
		print_r ( $data );
	}
	
	// 保存导入数据
	public function save_import($data) {
		// print_r($data);exit;
		$Goods = M ( 'Goods' );
		$add_time = date ( 'Y-m-d H:i:s', time () );
		foreach ( $data as $k => $v ) {
			if ($k >= 2) {
				$title = $v ['A'];
				$info [$k - 2] ['title'] = $title;
				
				$pno = $v ['B'];
				$result = $Goods->where ( array (
						'PNO' => $pno 
				) )->find ();
				if (! $result) {
					$info [$k - 2] ['PNO'] = $pno;
				}
				
				$old_pno = $v ['E'];
				$result = $Goods->where ( array (
						'old_PNO' => $old_pno 
				) )->find ();
				if ($result) {
					unset ( $data [$k] );
				} else {
					$info [$k - 2] ['old_PNO'] = $old_pno;
				}
				
				$brand_title = $v ['C'];
				$brand_id = M ( 'Brand' )->where ( array (
						'title' => $brand_title 
				) )->getField ( 'id' );
				if ($brand_id) {
					$info [$k - 2] ['brand_id'] = $brand_id;
				} else {
					$new_brand_id = M ( 'Brand' )->add ( array (
							'title' => $brand_title,
							'sort' => $k,
							'add_time' => $add_time 
					) );
					$info [$k - 2] ['brand_id'] = $new_brand_id;
				}
				
				$price = $v ['D'];
				$info [$k - 2] ['price'] = $price;
				
				$type_titles = $v ['F'];
				$type_array = explode ( ',', $type_titles );
				
				foreach ( $type_array as $type_info ) {
					$type_title = $type_info;
					$type_id = M ( 'Type' )->where ( array (
							'title' => $type_title 
					) )->getField ( 'id' );
					if ($type_id) {
						$info [$k - 2] ['type_ids'] .= $type_id . ',';
					} else {
						$new_type_id = M ( 'Type' )->add ( array (
								'title' => $type_title,
								'sort' => $k,
								'add_time' => $add_time 
						) );
						$info [$k - 2] ['type_ids'] .= ',' . $new_type_id . ',';
					}
				}
				
				$category_title = $v ['G'];
				$category_id = M ( 'Category' )->where ( array (
						'title' => $category_title 
				) )->getField ( 'id' );
				if ($category_id) {
					$info [$k - 2] ['category_id'] = $category_id;
				} else {
					$new_category_id = M ( 'Category' )->add ( array (
							'title' => $category_title,
							'sort' => $k,
							'add_time' => $add_time 
					) );
					$info [$k - 2] ['category_id'] = $new_category_id;
				}
				
				$info [$k - 2] ['add_time'] = $add_time;
				
				// print_r($info);exit;
				
				$result = $Goods->add ( $info [$k - 2] );
			}
		}
		
		if ($result) {
			$this->success ( '产品导入成功', 'Admin/Goods/index' );
		} else {
			$this->error ( '产品导入失败' );
		}
		// print_r($info);
	}
}
?>